package Hash;

public class HashBuck2 <K,V>{
    //利用泛型创建节点 - k , v 表示类型
    static class Node<K,V> {
        public K key;
        public V val;

        public Node<K, V> next;

        public Node(K key, V val) {
            this.val = val;
            this.key = key;
        }
    }
        public Node<K,V>[] array = (Node<K,V>[])new Node[10];
        public int usedSize;
        public static final double LOAD_FACTOR = 0.75;

        //字符串类型key时的插入和查找
        public void push(K key , V val){
            Node<K,V> node = new Node<K,V>(key, val);

            int hash = key.hashCode();
            int index = hash % array.length;

            Node<K,V> cur = array[index];

            while(cur != null){
                if(cur.key.equals(key)){
                    cur.val = val;
                    return;
                }
                cur = cur.next;
            }

            //头插法
            node.next = array[index];
            array[index] = node;
            usedSize++;

            if(doLoadFactor() >= LOAD_FACTOR){
                //处理重新哈希
                reSize();
            }
        }


        private void reSize(){
            Node<K,V>[] newArray =(Node<K, V>[]) new Node[array.length*2];
            for(int i = 0 ; i < array.length ; i++){
                Node<K,V> cur = array[i];
                while(cur != null){
                    int myval = cur.key.hashCode();
                    int index = myval% newArray.length;
                    Node<K, V> curNext = cur.next;

                    cur.next = newArray[index];
                    newArray[index] = cur;
                    cur = curNext;
                }
            }
            array = newArray;
        }

        //计算负载因子
        private double doLoadFactor(){
            return usedSize * 1.0 / array.length;
        }

        public V get(K key){
            int hash = key.hashCode();
            int index = hash % array.length;
            Node<K,V> cur = array[index];
            while(cur != null){
                if(cur.key.equals(key)){
                    return cur.val;
                }
                cur = cur.next;
            }
            return null;
        }

}
